<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Auth extends BaseController {
	var $_layoutPath = "templates/web/layout/layout";

	function Auth() {
		parent::BaseController();
		$this->output->enable_profiler ( TRUE );
		
		$this->load->library('Form_validation');
		$this->load->library('redux_auth');		
		
		$this->load->helper('url');
		$this->load->helper('form');
		
	}
	
	function index()
	{
		redirect("auth/status");
	}

	function login() {
		if ($this->redux_auth->logged_in())
	    {	
	    	echo "Ya te encuentras logado";
	    }
	    else
	    {
			$this->form_validation->set_rules('email', 'Email Address', 'trim|required|xss_clean');
		    $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
		    
	    	// Set captcha rules if login attempts exceed max attempts in config
			if ($this->redux_auth->is_max_login_attempts_exceeded()){
				$this->form_validation->set_rules('captcha', 'Captcha', 'trim|required|xss_clean|callback_captcha_check');
			}
		    
		    $this->_addData("show_captcha", FALSE);
		    
		    if ($this->form_validation->run() == false)
		    {
		    	if ($this->redux_auth->is_max_login_attempts_exceeded()){
		    		// Create catpcha
					$this->redux_auth->captcha();
					
		    		// Set view data to show captcha on view file
					$this->_addData("show_captcha", TRUE);
		    	}
		        $this->_render();
		    }
		    else
		    {
		        $email    = $this->input->post('email');
		        $password = $this->input->post('password');
		        
		        $login = $this->redux_auth->login($email, $password);
		        
		        if($login !== FALSE){
		        	redirect('');
		        } else{
		        	$this->_addError("Usuario no valido");
			        //Comprobaciones de si superamos el limite de intentos fallidos para lanzar el captcha...
			    	if ($this->redux_auth->is_max_login_attempts_exceeded()){
			    		// Create catpcha
						$this->redux_auth->captcha();
					
			    		// Set view data to show captcha on view file
						$this->_addData("show_captcha", TRUE);
			    	}
		        	$this->_render();
		        }
		    }
	    }
		
	}
	
	function captcha_check($code)
	{
		$result = TRUE;
		
		if ($this->redux_auth->is_captcha_expired())
		{
			// Will replace this error msg with $lang
			$this->form_validation->set_message('captcha_check', 'Tu codigo de confirmación ha expirado. Intentalo de nuevo.');			
			$result = FALSE;
		}
		elseif ( ! $this->redux_auth->is_captcha_match($code))
		{
			$this->form_validation->set_message('captcha_check', 'Tu codigo de confirmación no es correcto. Intentalo de nuevo.');			
			$result = FALSE;
		}

		return $result;
	}

	function logout() {
		$this->redux_auth->logout();
		redirect('');
	}
	
	function register(){
		$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|callback_username_check');
	    $this->form_validation->set_rules('email', 'Email Address', 'trim|required|xss_clean|callback_email_check|valid_email');
	    $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
	    
	    if ($this->form_validation->run() == false)
	    {
	        $this->_render();
	    }
	    else
	    {
	        $username = $this->input->post('username');
	        $email    = $this->input->post('email');
	        $password = $this->input->post('password');
	        
	        /** Campos adicionales **/
	        $additional = array();
	        
	    	$first_name = $this->input->post("first_name");
	        if($first_name != NULL && $first_name != ""){
	        	$additional['first_name'] = $first_name;
	        }
	        
	    	$last_name = $this->input->post("last_name");
	        if($last_name != NULL && $last_name != ""){
	        	$additional['last_name'] = $last_name;
	        }
	        
	        $register = $this->redux_auth->register($username, $password, $email, $additional);
	        
	        if ($register)
	        {
	            $this->session->set_flashdata('message', '<p class="success">You have now registered. Please login.</p>');
	            redirect('auth/register');
	        }
	        else
	        {
	            $this->session->set_flashdata('message', '<p class="error">Something went wrong, please try again or contact the helpdesk.</p>');
	            redirect('auth/register');
	        }
	    }
	}
	
	/**
	 * activate
	 * doesn't currently work
	 *
	 * @return void
	 * @author Mathew
	 **/
	function activate()
	{
	    $this->form_validation->set_rules('code', 'Verification Code', 'required');
	    $this->form_validation->set_error_delimiters('<p class="error">', '</p>');
	    
	    if ($this->form_validation->run() == false)
	    {
	        
	        $this->_render();
	    }
	    else
	    {
	        $code = $this->input->post('code');
			$activate = $this->redux_auth->activate($code);
		    
			if ($activate)
			{
				$this->session->set_flashdata('message', '<p class="success">Your Account is now activated, please login.</p>');
	            redirect('auth/activate');
			}
			else
			{
				$this->session->set_flashdata('message', '<p class="error">Your account is already activated or doesn\'t need activating.</p>');
	            redirect('auth/activate');
			}
	    }
	}
	
	/**
	 * Username check
	 *
	 * @return void
	 * @author Mathew
	 **/
	public function username_check($username)
	{
	    $check = $this->redux_auth_model->username_check($username);
	    
	    if ($check)
	    {
	        $this->form_validation->set_message('username_check', 'The username "'.$username.'" already exists.');
	        return false;
	    }
	    else
	    {
	        return true;
	    }
	}
	
	/**
	 * Email check
	 *
	 * @return void
	 * @author Mathew
	 **/
	public function email_check($email)
	{
	    $check = $this->redux_auth_model->email_check($email);
	    
	    if ($check)
	    {
	        $this->form_validation->set_message('email_check', 'The email "'.$email.'" already exists.');
	        return false;
	    }
	    else
	    {
	        return true;
	    }
	}
	
	/**
	 * Profile
	 *
	 * @return void
	 * @author Mathew
	 **/
	public function profile()
	{
	    if ($this->redux_auth->logged_in())
	    {
	        $profile = $this->redux_auth->profile();
	        
	        echo "<pre>";
		    print_r($profile);
		    echo "</pre>";
	    }
	    else
	    {
	        redirect('auth/login');
	    }
	}
	
	/**
	 * status
	 *
	 * @return void
	 * @author Mathew
	 **/
	function status()
	{
	    $status = $this->redux_auth->logged_in();
	    
	    echo "<pre>";
	    print_r($status);
	    echo "</pre>";
	}
	/**
	 * change password
	 *
	 * @return void
	 * @author Mathew
	 **/
	function change_password()
	{	    
	    $this->form_validation->set_rules('old', 'Old password', 'required');
	    $this->form_validation->set_rules('new', 'New Password', 'required|matches[new_repeat]');
	    $this->form_validation->set_rules('new_repeat', 'Repeat New Password', 'required');
	    $this->form_validation->set_error_delimiters('<p class="error">', '</p>');
	    
	    if ($this->form_validation->run() == false)
	    {
	        $data['content'] = $this->load->view('change_password', null, true);
	        $this->load->view('template', $data);
	    }
	    else
	    {
	        $old = $this->input->post('old');
	        $new = $this->input->post('new');
	        
	        $identity = $this->session->userdata($this->config->item('identity'));
	        
	        $change = $this->redux_auth->change_password($identity, $old, $new);
		
    		if ($change)
    		{
    			$this->logout();
    		}
    		else
    		{
    			echo "Password Change Failed";
    		}
	    }
	}
	
	/**
	 * forgotten password
	 *
	 * @return void
	 * @author Mathew
	 **/
	function forgotten_password()
	{
	    $this->form_validation->set_rules('email', 'Email Address', 'required');
	    $this->form_validation->set_error_delimiters('<p class="error">', '</p>');
	    
	    if ($this->form_validation->run() == false)
	    {
	        $data['content'] = $this->load->view('forgotten_password', null, true);
	        $this->load->view('template', $data);
	    }
	    else
	    {
	        $email = $this->input->post('email');
			$forgotten = $this->redux_auth->forgotten_password($email);
		    
			if ($forgotten)
			{
				$this->session->set_flashdata('message', '<p class="success">An email has been sent, please check your inbox.</p>');
	            redirect('welcome/forgotten_password');
			}
			else
			{
				$this->session->set_flashdata('message', '<p class="error">The email failed to send, try again.</p>');
	            redirect('welcome/forgotten_password');
			}
	    }
	}
	
	/**
	 * forgotten_password_complete
	 *
	 * @return void
	 * @author Mathew
	 **/
	public function forgotten_password_complete()
	{
	    $this->form_validation->set_rules('code', 'Verification Code', 'required');
	    $this->form_validation->set_error_delimiters('<p class="error">', '</p>');
	    
	    if ($this->form_validation->run() == false)
	    {
	        redirect('welcome/forgotten_password');
	    }
	    else
	    {
	        $code = $this->input->post('code');
			$forgotten = $this->redux_auth->forgotten_password_complete($code);
		    
			if ($forgotten)
			{
				$this->session->set_flashdata('message', '<p class="success">An email has been sent, please check your inbox.</p>');
	            redirect('welcome/forgotten_password');
			}
			else
			{
				$this->session->set_flashdata('message', '<p class="error">The email failed to send, try again.</p>');
	            redirect('welcome/forgotten_password');
			}
	    }
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
/**
	 * Create CAPTCHA image to verify user as a human
	 *
	 * @return	string
	 */
	function _create_captcha()
	{
		$this->load->plugin('captcha');

		$cap = create_captcha(array(
			'img_path'		=> './'.$this->config->item('captcha_path', 'tank_auth'),
			'img_url'		=> base_url().$this->config->item('captcha_path', 'tank_auth'),
			'font_path'		=> './'.$this->config->item('captcha_fonts_path', 'tank_auth'),
			'font_size'		=> $this->config->item('captcha_font_size', 'tank_auth'),
			'img_width'		=> $this->config->item('captcha_width', 'tank_auth'),
			'img_height'	=> $this->config->item('captcha_height', 'tank_auth'),
			'show_grid'		=> $this->config->item('captcha_grid', 'tank_auth'),
			'expiration'	=> $this->config->item('captcha_expire', 'tank_auth'),
		));

		// Save captcha params in session
		$this->session->set_flashdata(array(
				'captcha_word' => $cap['word'],
				'captcha_time' => $cap['time'],
		));

		return $cap['image'];
	}

	/**
	 * Callback function. Check if CAPTCHA test is passed.
	 *
	 * @param	string
	 * @return	bool
	 */
	function _check_captcha($code)
	{
		$time = $this->session->flashdata('captcha_time');
		$word = $this->session->flashdata('captcha_word');

		list($usec, $sec) = explode(" ", microtime());
		$now = ((float)$usec + (float)$sec);

		if ($now - $time > $this->config->item('captcha_expire', 'tank_auth')) {
			$this->form_validation->set_message('_check_captcha', $this->lang->line('auth_captcha_expired'));
			return FALSE;

		} elseif (($this->config->item('captcha_case_sensitive', 'tank_auth') AND
				$code != $word) OR
				strtolower($code) != strtolower($word)) {
			$this->form_validation->set_message('_check_captcha', $this->lang->line('auth_incorrect_captcha'));
			return FALSE;
		}
		return TRUE;
	}
	
	function users($group = -1){
		
		$config = array();
		if(is_numeric($group)){
			$config['group'] = $group;
		} else{
			$config['group_name'] = $group;
		}
		
		/*$config['query_search'] = "Sergio";
		$config['email'] = "mor";
		$config['order'] = "users_meta.first_name";
		$config['active'] = 1;*/
		
		$this->load->model("redux_auth_model");
		$users = $this->redux_auth_model->getAll($config);
		
		echo "<pre>";
		print_r($users);
		echo "</pre>";
	}
}
?>